#!/usr/bin/env python3
# coding: utf-8

# User Authentication Module
import json
import requests
from conf.configer import config
from mod.domain import DomainRepository
from logs.logger import logger


class UAM():
    def __init__(self):
        self.token = ''
        self.header = ''
        return

    def req(self):
        return

    def auth(self):
        url = DomainRepository().get('domain') + '/saas-auth/api/v1/access-token'
        logger.info(f'[+] Post {url}')
        uid, skey = config().get_cred()
        # logger.info(f'[+] Post {uid, skey}')
        if not all([uid, skey]):
            logger.error(f'[-] 用户ID, 密钥secureKey 为空! 获取token失败')
            return False

        data = {'userId': uid, 'secureKey': skey}
        rsp = requests.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps(data), verify=False)
        # print(rsp.text)
        r = json.loads(rsp.text)
        if r.get('status') != 'success':
            logger.error(f'[-] Auth failed {r}')
            return False
        self.token = r['token']
        self.header = {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"}
        return True